<template>
  <div class="ad-upload-container">
    <el-card class="ad-upload-card">
      <template #header>
        <div class="card-header">
          <h2>企业广告上传</h2>
          <p>在这里上传您的企业广告信息和宣传图片</p>
        </div>
      </template>
      
      <el-form 
        :model="adForm" 
        :rules="rules" 
        ref="adFormRef" 
        label-position="top" 
        class="ad-form"
      >
        <!-- 基本信息 -->
        <h3 class="form-section-title">基本信息</h3>
        <el-form-item label="广告标题" prop="title">
          <el-input v-model="adForm.title" placeholder="请输入广告标题" />
        </el-form-item>
        
        <el-form-item label="广告内容" prop="content">
          <el-input 
            v-model="adForm.content" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入广告内容描述" 
          />
        </el-form-item>
        
        <el-form-item label="链接地址" prop="linkUrl">
          <el-input v-model="adForm.linkUrl" placeholder="请输入广告链接地址（可选）" />
        </el-form-item>
        
        <!-- 时间设置 -->
        <h3 class="form-section-title">时间设置</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker 
                v-model="adForm.startDate" 
                type="datetime" 
                placeholder="选择开始日期时间（可选）"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker 
                v-model="adForm.endDate" 
                type="datetime" 
                placeholder="选择结束日期时间（可选）"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 竞价设置 -->
        <h3 class="form-section-title">竞价设置</h3>
        <el-form-item label="启用竞价" prop="enableBid">
          <el-switch v-model="adForm.enableBid" />
        </el-form-item>
        
        <el-form-item v-if="adForm.enableBid" label="竞价金额" prop="bidPrice">
          <el-input-number 
            v-model="adForm.bidPrice" 
            :min="0" 
            :precision="2" 
            :step="10"
            style="width: 100%"
            placeholder="请输入竞价金额" 
          />
        </el-form-item>
        
        <!-- 图片上传 -->
        <h3 class="form-section-title">宣传图片</h3>
        <el-form-item label="上传图片" prop="images">
          <el-upload
            class="ad-image-uploader"
            :action="uploadAction"
            :auto-upload="false"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            :on-exceed="handleExceed"
            :before-upload="beforeImageUpload"
            :limit="5"
            multiple
            list-type="picture-card"
          >
            <el-icon class="upload-icon"><Plus /></el-icon>
            <template #tip>
              <div class="upload-tip">
                支持JPG、PNG格式，单张不超过5MB，最多上传5张
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <!-- PDF宣传材料上传 -->
        <h3 class="form-section-title">PDF宣传材料</h3>
        <el-form-item label="上传PDF" prop="pdf">
          <el-upload
            class="pdf-uploader"
            :action="uploadAction"
            :auto-upload="false"
            :on-change="handlePdfChange"
            :on-remove="handlePdfRemove"
            :before-upload="beforePdfUpload"
            :limit="1"
            accept=".pdf"
          >
            <el-button type="primary">
              <el-icon class="el-icon--left"><Plus /></el-icon>选择PDF文件
            </el-button>
            <template #tip>
              <div class="upload-tip">
                支持PDF格式，文件大小不超过10MB，只能上传1个文件
              </div>
            </template>
            <template #file="{ file }">
              <div class="pdf-file-item">
                <el-icon class="pdf-icon"><Document /></el-icon>
                <div class="pdf-info">
                  <span class="pdf-name">{{ file.name }}</span>
                  <span class="pdf-size">{{ (file.size / 1024 / 1024).toFixed(2) }} MB</span>
                </div>
                <el-button 
                  type="danger" 
                  circle 
                  @click.stop="handlePdfRemove(file)"
                  class="pdf-remove-btn"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" :loading="loading" @click="submitForm">提交广告</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Document, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../../store/user'
import axios from 'axios'

const router = useRouter()
const userStore = useUserStore()
const adFormRef = ref(null)
const loading = ref(false)
const uploadAction = 'javascript:void(0)' // 禁用自动上传

// 表单数据
const adForm = reactive({
  title: '',
  content: '',
  linkUrl: '',
  startDate: null,
  endDate: null,
  bidPrice: 100,
  enableBid: false,
  images: [],
  pdf: null
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入广告标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入广告内容', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  linkUrl: [
    { 
      pattern: /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w.-]*)*\/?$/, 
      message: '请输入有效的URL地址', 
      trigger: 'blur' 
    }
  ],
  startDate: [
    { 
      validator: (rule, value, callback) => {
        if (adForm.endDate && value && value > adForm.endDate) {
          callback(new Error('开始日期不能晚于结束日期'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  endDate: [
    { 
      validator: (rule, value, callback) => {
        if (adForm.startDate && value && value < adForm.startDate) {
          callback(new Error('结束日期不能早于开始日期'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  bidPrice: [
    { 
      required: true, 
      message: '请输入竞价金额', 
      trigger: 'blur',
      type: 'number'
    }
  ],
  images: [
    { 
      validator: (rule, value, callback) => {
        if (value.length === 0) {
          callback(new Error('请至少上传一张宣传图片'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

// PDF上传前的验证
const beforePdfUpload = (file) => {
  const isPDF = file.type === 'application/pdf'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isPDF) {
    ElMessage.error('上传文件只能是PDF格式!')
  }
  if (!isLt10M) {
    ElMessage.error('上传PDF大小不能超过10MB!')
  }
  
  return isPDF && isLt10M
}

// 处理PDF变更
const handlePdfChange = (file) => {
  adForm.pdf = file.raw
}

// 处理PDF移除
const handlePdfRemove = () => {
  adForm.pdf = null
}

// 图片上传前的验证
const beforeImageUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isJPGOrPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB!')
  }
  
  return isJPGOrPNG && isLt5M
}

// 处理图片变更
const handleImageChange = (file, fileList) => {
  adForm.images = fileList
}

// 处理图片移除
const handleImageRemove = (file, fileList) => {
  adForm.images = fileList
}

// 处理超出限制
const handleExceed = () => {
  ElMessage.warning('最多只能上传5张图片')
}

// 重置表单
const resetForm = () => {
  ElMessageBox.confirm('确定要重置表单吗？所有已填写的内容将被清空', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    adFormRef.value.resetFields()
    adForm.images = []
    adForm.pdf = null
    ElMessage.success('表单已重置')
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  if (!userStore.token) {
    ElMessage.error('您尚未登录或登录已过期，请重新登录')
    router.push('/login')
    return
  }

  adFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请正确填写表单内容')
      return
    }

    loading.value = true
    try {
      // 准备表单数据
      const formData = new FormData()
      formData.append('title', adForm.title)
      formData.append('content', adForm.content)
      
      if (adForm.linkUrl) {
        formData.append('linkUrl', adForm.linkUrl)
      }
      
      if (adForm.startDate) {
        formData.append('startDate', adForm.startDate.toISOString())
      }
      
      if (adForm.endDate) {
        formData.append('endDate', adForm.endDate.toISOString())
      }
      
      // 修改为返回1或0
      formData.append('enableBid', adForm.enableBid ? 1 : 0)
      
      if (adForm.enableBid && adForm.bidPrice) {
        formData.append('bidPrice', adForm.bidPrice)
      }
      
      // 添加图片文件
      adForm.images.forEach(item => {
        formData.append('images', item.raw)
      })
      
      // 添加PDF文件
      if (adForm.pdf) {
        formData.append('pdf', adForm.pdf)
      }
      
      // 发送请求
      const response = await axios.post('http://localhost:3000/api/company-ad', formData, {
        headers: {
          'Authorization': `Bearer ${userStore.token}`,
          'Content-Type': 'multipart/form-data'
        }
      })
      
      ElMessage.success('广告提交成功')
      console.log('广告提交成功:', response.data)
      
      // 重置表单
      adFormRef.value.resetFields()
      adForm.images = []
      adForm.pdf = null
      
      // 可选：跳转到广告列表页面
      // router.push('/company/ad/list')
      
    } catch (error) {
      console.error('广告提交失败:', error)
      ElMessage.error(error.response?.data?.message || '广告提交失败，请稍后重试')
    } finally {
      loading.value = false
    }
  })
}
</script>

<style lang="scss" scoped>
.ad-upload-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.ad-upload-card {
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  
  .card-header {
    text-align: center;
    margin-bottom: 10px;
    
    h2 {
      font-size: 24px;
      color: #303133;
      margin-bottom: 8px;
    }
    
    p {
      color: #909399;
      font-size: 14px;
    }
  }
}

.ad-form {
  padding: 10px;
}

.form-section-title {
  font-size: 18px;
  color: #409EFF;
  margin: 25px 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #EBEEF5;
  
  &:first-child {
    margin-top: 0;
  }
}

.ad-image-uploader {
  :deep(.el-upload--picture-card) {
    width: 148px;
    height: 148px;
    line-height: 148px;
    border-radius: 8px;
    
    &:hover {
      border-color: #409EFF;
    }
  }
  
  .upload-icon {
    font-size: 28px;
    color: #8c939d;
  }
  
  .upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 10px;
  }
}

.pdf-uploader {
  width: 100%;
  
  .pdf-file-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    margin-top: 10px;
    background-color: #f5f7fa;
    border-radius: 8px;
    transition: all 0.3s;
    
    &:hover {
      background-color: #ecf5ff;
    }
    
    .pdf-icon {
      font-size: 24px;
      color: #f56c6c;
      margin-right: 12px;
    }
    
    .pdf-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      
      .pdf-name {
        font-size: 14px;
        color: #303133;
        margin-bottom: 4px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 300px;
      }
      
      .pdf-size {
        font-size: 12px;
        color: #909399;
      }
    }
    
    .pdf-remove-btn {
      margin-left: 12px;
    }
  }
  
  .upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 10px;
  }
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 30px;
  
  .el-button {
    min-width: 120px;
    padding: 12px 20px;
    font-size: 16px;
  }
}

// 响应式调整
@media (max-width: 768px) {
  .ad-upload-container {
    padding: 10px;
  }
  
  .ad-upload-card {
    .card-header {
      h2 {
        font-size: 20px;
      }
    }
  }
  
  .form-section-title {
    font-size: 16px;
  }
  
  .form-actions {
    flex-direction: column;
    
    .el-button {
      width: 100%;
    }
  }
  
  .pdf-file-item {
    .pdf-info {
      .pdf-name {
        max-width: 200px;
      }
    }
  }
}
</style>